# -*- coding: utf-8 -*-

from tablestore import *

from GKModel.BaseModel import BaseModel

CATEGORY_AD_AREA = 0
CATEGORY_ARTICLE = 1
CATEGORY_TUTOR = 2
CATEGORY_TUTOR_MATCH = 3


class Category(BaseModel):
    TABLE_NAME = 'Categories'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def query_by_key_name(self, gid, key, name):
        inclusive_start_primary_key = [('gid', gid), ('cid', INF_MIN)]
        exclusive_end_primary_key = [('gid', gid), ('cid', INF_MAX)]
        columns_to_get = []
        limit = 1

        cond = CompositeColumnCondition(LogicalOperator.AND)
        cond.add_sub_condition(SingleColumnCondition('key', key, ComparatorType.EQUAL))
        cond.add_sub_condition(SingleColumnCondition('name', name, ComparatorType.EQUAL))

        try:
            consumed, next_start_primary_key, row_list, next_token = self.ots_client.get_range(
                table_name=Category.TABLE_NAME,
                direction=Direction.FORWARD,
                inclusive_start_primary_key=inclusive_start_primary_key,
                exclusive_end_primary_key=exclusive_end_primary_key,
                columns_to_get=columns_to_get,
                column_filter=cond,
                limit=limit,
                max_version=1
            )

            if row_list is not None and len(row_list) != 0:
                result = dict(row_list[0].primary_key)
                for att in row_list[0].attribute_columns:
                    result[att[0]] = att[1]
                return result
            else:
                raise ValueError(10000010, 'Invalid Key or Name')
        except OTSClientError as e:
            raise ValueError(1000020, e.get_error_message())
        except OTSServiceError as e:
            raise ValueError(1000020, e.get_error_message())


def new(**kwargs) -> Category:
    return Category(**kwargs)
